package com.chaodev.base.controller;

import cn.hutool.core.codec.Base64Encoder;
import com.alibaba.fastjson.JSONObject;
import com.chaodev.base.base.RedisDao;
import com.chaodev.base.model.LoginUser;
import com.chaodev.base.model.Result;
import com.chaodev.base.model.ResultEnum;
import com.chaodev.base.model.UserInfo;
import com.chaodev.base.utils.Base64EnOut;
import com.chaodev.base.utils.JwtUtil;
import com.chaodev.base.utils.ValidateCode;
import com.chaodev.base.service.ILogService;
import com.chaodev.base.service.ILoginService;
import io.swagger.annotations.*;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.env.Environment;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping(value = "/user")
public class LoginController {
    private static final Logger logger = LogManager.getLogger();
    @Autowired
    private RedisDao redisDao;

    @Autowired
    private ILoginService loginService;

    @Autowired
    private ILogService logService;

    @Value("${myserver.name}")
    private String myServerName;
    @Value("${variables.tokenExpireTime}")
    private long expireTime;

    @Resource
    Environment env;

    @ResponseBody
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    @ApiOperation(value = "用户登录")
    public Result login(HttpServletRequest request, HttpServletResponse response, @RequestBody @ApiParam(value = "134") LoginUser loginUser) {
        UserInfo userInfo = new UserInfo();
        UserInfo userInfo2=new UserInfo();
//        logger.warn("今天天气不错");
//        Base64EnOut base64EnOut = new Base64EnOut();
        userInfo.setUserId(Base64EnOut.Decode(loginUser.getUsercode()));
        //-1：验证码过期；-2：工号无效！；-3：工号被锁定；-4：密码输入错误！；-5：密码已过期！；-6：密码强度不够！；-7：验证码错误！；-8：后台出现错误！；-9：无默认账套！
        Result result = new Result();
        result.setServerID(myServerName);
        result.setData(userInfo);
        try {
            String sessionID = loginUser.getSessionID();
            if (!redisDao.existsKey(sessionID)) {
                result.setCode(ResultEnum.EREOR.getCode());
                result.setMsg("验证码过期!");
                return result;
            }
            String captcha = loginUser.getCaptcha().toUpperCase();
            String redisCaptcha = (String) redisDao.vGet(sessionID);
            //判断验证码是否正确
            if (!captcha.equals(redisCaptcha)) {
                result.setCode(-7);
                result.setMsg("验证码错误！");
                return result;
            }
            redisDao.delete(sessionID);
            String userName = Base64EnOut.Decode(loginUser.getUsercode());
            String userPass = Base64EnOut.Decode(loginUser.getPassword());
            String ip = request.getRemoteAddr();
            HashMap<String, Object> mapIn = new HashMap<>();
            mapIn.put("username", userName);
            mapIn.put("password", userPass);
            mapIn.put("ip", ip);
            Result result1= loginService.login(mapIn);
//            String  resResult= mapIn.get("P_RESULT").toString();
//            if (resResult.equals("YES")) {
//                ArrayList<UserInfo> info = (ArrayList<UserInfo>) mapIn.get("v_cursor");
            if (result1.getCode()==0) {
                userInfo = (UserInfo) result1.getData();
                String userId = userInfo.getUserName();
                byte[] b = userId.getBytes("UTF-8");
                userId = new String(b, "UTF-8");
                String roleId=userInfo.getRoleName();
                byte[] c = roleId.getBytes("UTF-8");
                roleId = new String(c, "UTF-8");
                String departId=userInfo.getDepartName();
                byte[] d = departId.getBytes("UTF-8");
                departId = new String(d, "UTF-8");
                String skin=userInfo.getUserSkin();
                byte[] s = skin.getBytes("UTF-8");
                skin = new String(s, "UTF-8");
                String token = JwtUtil.createToken(userInfo.getUserId(),userId, userInfo.getDepartId(), userInfo.getRoleId(),roleId,departId,userInfo.getRealAccNbr(),userInfo.getAreaCode(),"","","","",skin);
//                redisDao.vSet(token, userInfo,600*60L);
//                redisDao.vSet(token, userInfo,expireTime);
                String array = JSONObject.toJSONString(userInfo);

                redisDao.vSet(token, array,expireTime);
                redisDao.vSet("expt"+token,System.currentTimeMillis(),expireTime);
                // TODO: 2022/1/17 测试完成后注释
//                System.out.println(token);
                result.setCode(ResultEnum.SUCCESS.getCode());
                result.setData(token);
                result.setMsg("登录成功");
                logService.logAdd(loginUser.toString(), "用户登录", "SUCCESS", result.toString(), userInfo2, request);
            } else {
                String[] aa = result1.getMsg().split("\\|");
                result.setCode(Integer.parseInt(aa[0]));
                result.setMsg(aa[1]);
                logService.logAdd(loginUser.toString(), "用户登录", "ERROR", result.toString(), userInfo2, request);
            }

        } catch (Exception ex) {
            ex.printStackTrace();
            result.setCode(-8);
            result.setMsg(ex.getMessage());
            logService.logAdd(loginUser.toString(), "用户登录", "ERROR", result.toString(), userInfo2, request);
        }
        return result;
    }

    @ResponseBody
    @ApiOperation(value = "获取图片验证码")
    @RequestMapping(value = "/getValidateCode", method = RequestMethod.GET)
    @ApiImplicitParam(name = "timestamp", paramType = "query", value = "参入时间戳，防止验证码不刷新", dataType = "string", required = true)
    public Result getValidateCode(HttpServletRequest request, HttpServletResponse response) {
        UserInfo userInfo = new UserInfo();
        UserInfo userInfo2=new UserInfo();
        Result result = new Result();
        result.setServerID(myServerName);

        // 设置响应的类型格式为图片格式
        response.setContentType("image/jpeg");
        //禁止图像缓存。
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        ValidateCode vCode = new ValidateCode(120, 30, 4, 50);//生成图片验证码
        String sessionID = request.getSession().getId();
        response.addHeader("sessionid", sessionID);
        response.addHeader("serverID", myServerName);

        long exireTime = 120;
        System.out.println("验证码："+vCode.getCode());
        Boolean savet = redisDao.vSet(sessionID, vCode.getCode(), exireTime);//写入缓存
        if (savet) {
            try {
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                ImageIO.write(vCode.getBuffImg(),"png",baos);
                String img = Base64Encoder.encode(baos.toByteArray());
                Map<String,String> msg = new HashMap<>();
                msg.put("sessionId",sessionID);
                msg.put("img","data:image/jpg;base64,"+img);
                result.setCode(ResultEnum.SUCCESS.getCode());
                result.setData(msg);
                result.setMsg("验证码获取成功!");
            } catch (Exception ex) {
                ex.printStackTrace();
                result.setCode(ResultEnum.EREOR.getCode());
                result.setMsg(ex.getMessage());
            }
        } else {
            result.setCode(ResultEnum.EREOR.getCode());
            result.setMsg("图形验证码写入redis失败");
        }
        return result;
    }

    @RequestMapping(value = "logout", method = RequestMethod.GET)
    @ApiImplicitParam(name = "token", paramType = "header", value = "token", dataType = "string", required = true)
    @ApiOperation(value = "注销登录")
    public Result logout(HttpServletRequest request, HttpServletResponse response) {
        Result result = new Result();
        String token = request.getHeader("token");
        UserInfo userInfo = new UserInfo();
        result.setServerID(myServerName);
        try {
            userInfo = JwtUtil.getUserInfoFromToken(token,redisDao);
            redisDao.delete(token);
            redisDao.delete("expt"+token);
            result.setCode(0);
            result.setMsg("注销成功");
            logService.logAdd("", "注销登录", "SUCCESS", result.toString(), userInfo, request);
        } catch (Exception ex) {
            result.setCode(-1);
            result.setMsg(ex.getMessage());
            logService.logAdd("", "注销登录", "ERROR", result.toString(), userInfo, request);
        }
        return result;
    }


    /**
     * 功能描述:
     * 〈OA单点登录〉
     * @return : ModelAndview
     * @author : mxh
     * @date:  2020-06-11 10:23:21
     */
//    @RequestMapping(value="/SigleLogin")
//    @ApiOperation(value = "用户登录")
//    public void sigleLogin(HttpServletRequest request, HttpServletResponse response, HttpSession session) throws Exception {
//        String token = request.getParameter("token");
//        String loginsys=request.getParameter("sysid");
////        String typecode = request.getParameter("type");
//        Result loginResult = new Result();
////        &&!StringHelper.empty(typecode)
//        if (!StringHelper.empty(token)) {
////        if (true){
//            String url="";
//            if(!StringHelper.empty(loginsys))
//            {
//                url = env.getProperty("AuthAddressMH");
//            }
//            else
//            {
//                url = env.getProperty("AuthAddress");
//            }
//            JSONObject json = new JSONObject();
//            json.put("TOKEN", token);
//            try {
//                String result= HttpClientUtil.httpPut(url,json.toString());
//                if (!StringHelper.empty(result)) {
////                    if (true){
//                    JSONObject jsonObject = JSON.parseObject(result);
//                    boolean success = jsonObject.getBoolean("success");
//                    if (success) {
////                        if (true){
//                        JSONObject resultData = jsonObject.getJSONObject("resultData");
//                        String logName = resultData.getString("LOGNAME");
////                        String logName = "admin";
//                        System.out.print(logName);
//                        String IP = request.getRemoteAddr();
//                        Map<String, Object> requestMap = new HashMap<>();
//                        requestMap.put("ip", IP);
//                        requestMap.put("username", resultData.getString("LOGNAME"));
////                        requestMap.put("username",logName);
//                        loginResult = loginService.SigleLogin(requestMap, request, response);
//                        System.out.println("验证==》"+loginResult.getCode());
//                        int code =loginResult.getCode();
//                        if (code==0) {
//                            if(!StringHelper.empty(loginsys))
//                            {
//                                response.sendRedirect(env.getProperty("zbzIndexnew")+"?token="+loginResult.getData());
//                            }
//                            else
//                            {
//                                response.sendRedirect(env.getProperty("zbzIndex")+"?token="+loginResult.getData());
//                            }
//                        } else {
//                            response.sendRedirect(env.getProperty("zbzLogin"));
//                        }
//                    }else{
//                        response.sendRedirect(env.getProperty("zbzLogin"));
//                    }
//                }
//            } catch (Exception e) {
//                logService.logAdd("", "单点登录", "ERROR", loginResult.getData().toString(), null, request);
//            }
//        }else{
//            response.sendRedirect(env.getProperty("zbzLogin"));
//        }
//    }
    @ApiOperation(value = "检查用户是否登录")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token", paramType = "header", value = "token", dataType = "string", required = true),
    })
    @GetMapping("loginCheck")
    public Result loginCheck(HttpServletRequest request, HttpServletResponse response){
        String token = request.getHeader("token");
        UserInfo userInfo = new UserInfo();
        userInfo = JwtUtil.getUserInfoFromToken(token,redisDao);
        Result result = new Result();
        if(null==userInfo){
            result.setCode(ResultEnum.EREOR.getCode());
            result.setMsg("凭证已过期，请重新登录");
            return result;
        }
        result.setCode(ResultEnum.SUCCESS.getCode());
        result.setData(userInfo);
        result.setMsg("操作成功");
        return result;
    }

}
